#include"udp.server.hh"

void usage(char* proc)
{
    std::cout<<"\nUsage: "<<proc<<" ip  port\n";
}
//127.0.0.1 本地環迴
// ./udp_client 127.0.0.1 8080
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        usage(argv[0]);
        exit(1);
    }
    //還是先創建套接字
    int sock=socket(AF_INET,SOCK_DGRAM,0);//AF_INET==PF_INET
    if(sock<0)
    {
        std::cerr << errno << ":" << strerror(errno) << endl;
            exit(2);
    }
    //客戶的要不要綁定？
    char buffer[1024];
    string message;
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));//bzero()是一樣的
    server.sin_family=AF_INET;
    server.sin_addr.s_addr=inet_addr(argv[1]);//這一點要重點注意一下
    server.sin_port=htons(atoi(argv[2]));
    while(1)
    {
        cout<<"請輸入你想發送的信息：";
        getline(cin,message);
        if(message=="quit") break;
        //儅client第一次給服務器發送消息時，OS會自動給client bind他的IP和Port
        sendto(sock,message.c_str(),message.size(),0,(struct sockaddr*)&server,sizeof(server));

        struct sockaddr_in tmp;
        socklen_t len=sizeof(tmp);
        ssize_t s=recvfrom(sock,buffer,sizeof(buffer),0,(struct sockaddr*)&tmp,&len);
        if(s>0)
        {
            buffer[s]=0;
            cout<<"server echo: "<<buffer<<endl;
        }
    }
    close(sock);
    return 0;
}
